package org.linlinjava.litemall.wx.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.db.domain.LitemallCdkey;
import org.linlinjava.litemall.db.domain.LitemallCompanyCharge;
import org.linlinjava.litemall.db.domain.LitemallPriceHistory;
import org.linlinjava.litemall.db.domain.LitemallUser;
import org.linlinjava.litemall.db.service.LitemallCdkeyService;
import org.linlinjava.litemall.db.service.LitemallCompanyChargeService;
import org.linlinjava.litemall.db.service.LitemallPriceHistoryService;
import org.linlinjava.litemall.db.service.LitemallUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class WxCdkeyService {

    private final Log logger = LogFactory.getLog(WxCdkeyService.class);

    @Autowired
    private LitemallUserService userService;

    @Autowired
    private LitemallCdkeyService cdkeyService;
    @Autowired
    private LitemallPriceHistoryService priceHistoryService;

    /**
     * 兑换
     * <p>
     */
    @Transactional
    public Object conversion(Integer userId, LitemallCdkey cdkey) {
        if (userId == null) {
            return ResponseUtil.unlogin();
        }
        LitemallUser user = userService.findById(userId);
        cdkey.setMemberId(userId);
        cdkey.setStatus(true);
        cdkeyService.updateById(cdkey);
        LitemallPriceHistory priceHistory = new LitemallPriceHistory();
        priceHistory.setMallPrice(cdkey.getFaceValue());
        priceHistory.setHistoryType(LitemallPriceHistoryService.CONVERSION_TYPE);
        priceHistory.setMemberId(userId);
        priceHistory.setRelationId(cdkey.getId().toString());
        priceHistoryService.add(priceHistory);
        if(user.getMallMoney() != null) {
            user.setMallMoney(user.getMallMoney().add(cdkey.getFaceValue()));
        }else{
            user.setMallMoney(cdkey.getFaceValue());
        }
        userService.updateById(user);
        return null;
    }
}
